<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head th:include="template::head">

</head>
<body class="hold-transition sidebar-mini sidebar-collapse ng-cloak" ng-app="ESL" style="min-width: 1200px">
<div class="wrapper" ng-controller="user_manager">
  <!-- Navbar -->
    <header th:include="template::header"></header>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 th:text="#{menu_user_manager}">用户管理</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active" th:text="#{menu_user_manager}">用户管理</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="row">
        <div class="col-12">

          <!-- /.card -->

          <div class="card">
            <!-- /.card-header -->
            <div class="card-body ">
              <div class="">
                <input type="text" id="username_search" ng-model="search.username" th:placeholder="#{user_manager_username}"/>
                <input sec:authorize="hasRole('ROLE_SUPPERADMIN')" type="text" id="sourceFlag_search" ng-model="search.sourceFlag" th:placeholder="#{store_manager_sourceFlag}"/>
                <button ng-click="loadItems()" class="btn btn-sm btn-primary" th:text="#{action.search}">查询</button>
                <button ng-click="reset()" class="btn btn-sm btn-primary">重置</button>
                <button ng-click="openEdit($event)" class="btn btn-sm btn-success">新增</button>

              </div>
              <div class="table-responsive">
              <table id="tab1" class="table table-bordered table-hover table-condensed" >
                <thead>
                <tr>
                  <th><input type="checkbox"  ng-model="selectAll"   ng-change="changeAll($event)"/></th>
                  <th></th>
                  <th style="white-space: nowrap;"  ><i id="id_sort_icon_username" class="fa fa-fw fa-sort" ng-click="sortBy('username')"></i><span th:text="#{user_manager_username}"></span></th>
                  <th style="white-space: nowrap;" ><i id="id_sort_icon_modifyTime" class="fa fa-fw fa-sort" ng-click="sortBy('modifyTime')"></i><span th:text="#{user_manager_modify_time}"></span> </th>
                  <th style="white-space: nowrap;" ><i id="id_sort_icon_remark" class="fa fa-fw fa-sort" ng-click="sortBy('remark')"></i><span th:text="#{user_manager_remark}"></span> </th>
                  <th style="white-space: nowrap;"  sec:authorize="hasRole('ROLE_SUPPERADMIN')"><i id="id_sort_icon_expireTime" class="fa fa-fw fa-sort" ng-click="sortBy('expireTime')"></i><span th:text="#{user_manager_expireTime}"></span> </th>
                  <th style="white-space: nowrap;"  sec:authorize="hasRole('ROLE_SUPPERADMIN')"><i id="id_sort_icon_status" class="fa fa-fw fa-sort" ng-click="sortBy('status')"></i><span th:text="#{user_manager_status}"></span> </th>
                  <th style="white-space: nowrap;"  sec:authorize="hasRole('ROLE_SUPPERADMIN')"><i id="id_sort_icon_sourceFlag" class="fa fa-fw fa-sort" ng-click="sortBy('sourceFlag')" ></i><span >资源标识</span></th>
                  <th style="white-space: nowrap;"  ><i id="id_sort_icon_modifyWho" class="fa fa-fw fa-sort" ng-click="sortBy('modifyWho')"></i><span >修改人</span></th>
                  <th style="white-space: nowrap;"  ><i id="id_sort_icon_roles" class="fa fa-fw fa-sort" ng-click="sortBy('roles')"></i><span >角色权限</span></th>
                  <th style="white-space: nowrap;"  ><i id="id_sort_icon_stores" class="fa fa-fw fa-sort" ng-click="sortBy('stores')"></i><span >门店</span></th>
                  <th style="white-space: nowrap;" th:text="#{action.operation}"></th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="sys_user in userList" ng-click="changeCurrents(sys_user,$event)">

                  <td>
                    <label>
                    <input type="checkbox" value="{{sys_user.id}}" ng-model="sys_user.checked" name="checkbox" ng-click="changeCurrent(sys_user,$event)"/>
                    </label>
                  </td>

                  <td>{{$index+1}}</td>
                  <td>{{sys_user.username}}</td>
                  <td>{{sys_user.modifyTime|date:'yyyy/MM/dd HH:mm:ss'}}</td>
                  <td>{{sys_user.remark}}</td>
                  <td  sec:authorize="hasRole('ROLE_SUPPERADMIN')">{{sys_user.expireTime|date:'yyyy/MM/dd HH:mm:ss'}}</td>
                  <td ng-if="sys_user.status==0"  sec:authorize="hasRole('ROLE_SUPPERADMIN')">启用</td>
                  <td ng-if="sys_user.status==1"  sec:authorize="hasRole('ROLE_SUPPERADMIN')">禁用</td>
                  <td sec:authorize="hasRole('ROLE_SUPPERADMIN')">{{sys_user.sourceFlag}}</td>
                  <td>{{sys_user.modifyWho}}</td>
                  <td>
                    <span ng-repeat="role in sys_user.roles">{{role.roleName}},</span>
                  </td>
                  <td>
                    <span ng-repeat="store in sys_user.stores">{{store.storeName}},</span>
                  </td>
                  <td style="white-space: nowrap;">
                    <button ng-click="openEdit($event,sys_user)" class="btn btn-sm btn-default">修改</button>
                    <button ng-click="openRelate($event,sys_user)" class="btn btn-sm btn-warning">关联</button>
                    <button ng-click="openRemovePopup($event,sys_user)" class="btn btn-sm btn-danger">删除</button>
                  </td>
                </tr>
                </tbody>
              </table>
              </div>

              <!--page plugin-->
              <navigation th:include="template::page"></navigation>
              </div>

            </div>

            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      <!-- /.row -->
      <div class="modal fade" id="remove_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-sm" role="document" style="margin-top:300px;">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title" id="id_remove_modal_title"  th:text="#{sku.removeAlertMsg}"></h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <span style="color:red">删除用户：{{current.username}}</span>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{action.close}"></button>
              <button type="button" class="btn btn-primary" ng-click="deleteUser()" th:text="#{action.confirm}"></button>
            </div>
          </div>
        </div>
      </div>


      <!--新增用户模态框 -->
      <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">

              <h4 class="modal-title" id="addModalLabel">
                编辑
              </h4>
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                &times;
              </button>
            </div>
            <div class="modal-body">
                  <p ng-show="current.error" style="color:red">{{current.error}}</p>
                  <p>
                    用&nbsp&nbsp户&nbsp&nbsp名：<input  type="text" ng-model="current.username" ng-change="usernameChange()"/>
                    <span ng-show="!addCheckUsername()" style="color:red">用户名不小于4位</span>
                  </p>
                <p>
                    密&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp码：<input  type="password" ng-model="current.password" />
                    <span ng-show="!addCheckPassword()" style="color:red">密码不小于6位</span>
                </p>

                <p>
                    确认密码：&nbsp<input  type="password" ng-model="current.pwdConfirm"/>
                    <span ng-show="!addCheckPwdConfirm()" style="color:red">两次输入不一致</span>
                </p>

                <p sec:authorize="hasRole('ROLE_SUPPERADMIN')">
                  资源标识：&nbsp<input  type="text" ng-model="current.sourceFlag"/>
                  <span ng-show="!addCheckSourceFlag()" style="color:red">资源标识不能空</span>
                </p>
                <p sec:authorize="hasRole('ROLE_SUPPERADMIN')">
                  过期时间：&nbsp<input  type="date" ng-model="current.expireTime"/>
                  <span ng-show="!addCheckExpireTime()" style="color:red">过期时间不能空</span>
                </p>
                  <p>
                    备&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp注：<textarea ng-model="current.remark"></textarea>
                  </p>

                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button type="button" class="btn btn-primary" ng-disabled="!addCheckAll()" ng-click="addSubmit()">
                      提交更改
                    </button>
                  </div>

            </div>

          </div><!-- /.modal-content -->
        </div><!-- /.modal -->
      </div>


        <!--编辑用户 模态框-->
      <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">

              <h4 class="modal-title" id="editModalLabel">
                编辑
              </h4>
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                &times;
              </button>
            </div>
            <ul  class="nav nav-tabs">
              <li class="nav-item">
                <a href="#editUserInfo" data-toggle="tab" class="nav-item nav-link active" >
                  修改信息
                </a>
              </li>
              <li class="nav-item">
                <a href="#changePwd" data-toggle="tab" class="nav-item nav-link" >
                  修改密码
                </a>
              </li>
            </ul>
            <div class="modal-body">
              <div  class="tab-content">
                <div class="tab-pane fade active show" id="editUserInfo">
                  <p ng-show="current.error" style="color:red">{{current.error}}</p>
                  <p>
                    用&nbsp&nbsp户&nbsp&nbsp名：<input  type="text" ng-model="current.username" ng-disabled="true" />
                  </p>


                  <p sec:authorize="hasRole('ROLE_SUPPERADMIN')">
                    资源标识：&nbsp<input  type="text" ng-model="current.sourceFlag"/>
                    <span ng-show="!addCheckSourceFlag()" style="color:red">资源标识不能空</span>
                  </p>
                  <p sec:authorize="hasRole('ROLE_SUPPERADMIN')">
                    过期时间：&nbsp<input  type="date" ng-model="current.expireTime"/>
                    <span ng-show="!addCheckExpireTime()" style="color:red">过期时间不能空</span>
                  </p>
                  <p sec:authorize="hasRole('ROLE_SUPPERADMIN')">
                    账号状态：&nbsp
                    <select ng-model="current.status">
                      <option selected="{{current.status==1}}" ng-value="0">启用</option>
                      <option selected="{{current.status==1}}" ng-value="1">禁用</option>
                    </select>

                  </p>
                  <p>
                    备&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp注：<textarea ng-model="current.remark"></textarea>
                  </p>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button type="button" class="btn btn-primary"  ng-click="addSubmit()"  ng-disabled="!editCheckAll()">
                      提交更改
                    </button>
                  </div>
                </div>
                <div class="tab-pane fade" id="changePwd">
                  <p>
                    密&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp码：<input  type="password" ng-model="current.pwd" />
                    <span ng-show="!changeCheckPassword()" style="color:red">密码不小于6位</span>
                  </p>

                  <p>
                    确认密码：&nbsp<input  type="password" ng-model="current.pwdConfirm"/>
                    <span ng-show="!changeCheckPwdConfirm()" style="color:red">两次输入不一致</span>
                  </p>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                    </button>
                    <button type="button" class="btn btn-primary" ng-disabled="!changePasswordCheckAll()" ng-click="addSubmitChangePwd()">
                      提交更改
                    </button>
                  </div>
                </div>
              </div>

              </div>

          </div><!-- /.modal-content -->
        </div><!-- /.modal -->
      </div>

      <!-- 关联模态框（Modal） -->
      <div class="modal fade" id="relateModal" tabindex="-1" role="dialog" aria-labelledby="relateModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">

              <h4 class="modal-title" id="relateModalLabel">
                关联角色/门店(<span style="color:deepskyblue">{{current.username}}</span>)
              </h4>
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                &times;
              </button>
            </div>
            <ul  class="nav nav-tabs">
              <li class="nav-item">
                <a href="#relateRole" data-toggle="tab" class="nav-item nav-link active" >
                  设置权限
                </a>
              </li>
            </ul>
            <div class="modal-body">

              <div id="myTabContent" class="tab-content">
                <div class="tab-pane fade active show" id="relateRole">
                  <ul>
                    <li ng-repeat="role in roleList">
                      <input type="checkbox" id="{{'roleCheckBox'+$index}}" ng-model="role.checked" ng-value="role.id"/>
                      <label for="{{'roleCheckBox'+$index}}">{{role.roleName}}</label>
                    </li>

                  </ul>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" ng-click="saveRoleRelate()">提交更改</button>
                  </div>
                </div>

              </div>
            </div>

          </div><!-- /.modal-content -->
        </div><!-- /.modal -->
      </div>
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  <footer th:include="template::footer"></footer>
  <!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->

<navigation th:include="template::js"></navigation>
<script th:inline="javascript">


    var top_page=[[#{page.top_page}]]
    var previous_page= [[#{page.previous_page}]]
    var next_page= [[#{page.next_page}]]
    var tail_page=[[#{page.tail_page}]]
    var eslApp=angular.module('ESL',[])

  eslApp.controller('user_manager',function ($scope,$http) {
      $scope.search ={};
      $scope.userList=[]
      $scope.menu={"user":true}
      $scope.current={};
      $scope.count = 0;//已选择数量



      //---start   新增/编辑用户
      $scope.addCheckUsername=function () {
          return $scope.current.username&&$scope.current.username.length>=4
      }

      $scope.addCheckPassword=function () {
          return $scope.current.password&&$scope.current.password.length>=6
      }
      $scope.addCheckPwdConfirm=function () {
          return $scope.current.pwdConfirm==$scope.current.password
      }

      $scope.addCheckSourceFlag=function () {

          return $scope.current.sourceFlag||$scope.current.sourceFlag=="0";
      }
      $scope.addCheckExpireTime=function () {
          return $scope.current.expireTime;
      }
      $scope.addCheckAll=function () {
          return $scope.addCheckUsername&&$scope.addCheckPassword()&&$scope.addCheckPwdConfirm()&&!$scope.current.error
      }
      //---end  新增/编辑用户

      $scope.editCheckAll=function () {
          return $scope.addCheckUsername && !$scope.current.error
      }

       //------start   修改密码检验
      $scope.changeCheckPassword=function () {
          return $scope.current.pwd&&$scope.current.pwd.length>=6
      }
      $scope.changeCheckPwdConfirm=function () {
          return $scope.current.pwdConfirm==$scope.current.pwd
      }
      $scope.changePasswordCheckAll=function () {
          return $scope.changeCheckPassword()&&$scope.changeCheckPwdConfirm()&&!$scope.current.error
      }
      //-----end   修改密码


      $scope.usernameChange=function () {
          $scope.current.error=null
      }

      /**
        新增/修改user提交
       */
    $scope.addSubmit=function () {
        console.log($scope.current)
         $http({
             method:"post",
             url:"/user_rest/add_change_user",
             data:$scope.current,
             headers:{'Content-Type': 'application/json'}
         }).success(function (json) {
             if(json.cmd=="success"){
                 $scope.loadItems()
                 angular.element("#addModal").modal("hide");
                 angular.element("#editModal").modal("hide");
                 alertSuccess()
             }else{
                 $scope.current.error=json.msg
             }

         }).error(function (json) {
             $scope.current.error=json.message
         })
    }

      $scope.addSubmitChangePwd=function () {
        var params={id:$scope.current.id,password:$scope.current.pwd}
          $http({
              method:"post",
              url:"/user_rest/change_password",
              data:params,
              headers:{'Content-Type': 'application/x-www-form-urlencoded'},
              transformRequest: function(obj) {
                  var str = [];
                  for (var s in obj) {
                      str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                  }
                  return str.join("&");
              }
          }).success(function (json) {
              if(json.cmd=="success"){
                  $scope.loadItems()
                  angular.element("#editModal").modal("hide");
                  alertSuccess()
              }else{
                  $scope.current.error=json.msg
              }

          }).error(function (json) {
              $scope.current.error=json.message
          })
      }


      /**
       * 保存user与角色关联关系
       */
    $scope.saveRoleRelate=function () {
        var roleIDs=[];
        angular.forEach($scope.roleList,function (item) {
            if(item.checked){
                roleIDs.push(item.id)
            }
        })
      $http({
          url:"/user_rest/save_role_relate",
          data:{roleIDs:roleIDs,userId:$scope.current.id},
          method:"post"
      }).success(function (json) {
          angular.element("#relateModal").modal("hide");
          if(json.cmd!="success"){
              alert("操作失败")
              return;
          }

          alertSuccess()
          $scope.loadItems()
      }).error(function (json) {
          angular.element("#relateModal").modal("hide");
          alert(json.message)
      })
    }
      /**
       * 保存user与门店关联关系
       */
    $scope.saveStoreRelate=function () {
        var storeCodes=[];
        angular.forEach($scope.storeList,function (item) {
            if(item.checked){
                storeCodes.push(item.storeCode)
            }
        })
        $http({
            url:"/user_rest/save_store_relate",
            data:{storeCodes:storeCodes,userId:$scope.current.id},
            method:"post"
        }).success(function (json) {
            angular.element("#relateModal").modal("hide");
            if(json.cmd=="success"){
                alertSuccess();
                $scope.loadItems()
            }else{
                alert("操作失败")
            }



        }).error(function (json) {
            angular.element("#relateModal").modal("hide");
            alert(json.message)
        })
    }
      //点击单个checkbox
      $scope.changeCurrent = function(current, $event) {
          // //计算已选数量 true加， false减
          $scope.count += current.checked ? 1 : -1;
          //判断是否全选，选数量等于数据长度为true
          $scope.selectAll = $scope.count=== $scope.userList.length;
          //


          $event.stopPropagation();//阻止冒泡

      };

      //单击行选中
      $scope.changeCurrents = function(current, $event) {
          if(current.checked == undefined){
              current.checked = true;
          }else{
              current.checked = !current.checked;
          }
          $scope.changeCurrent(current, $event);
      };

//全选（取消全选
      $scope.changeAll = function($event) {
          angular.forEach($scope.userList, function(item) {
              item.checked = $scope.selectAll;
          });
          $scope.count = $scope.selectAll ? $scope.userList.length : 0;

      };





      $scope.gotoPage = function(page) {
          if(page!=0&&!page||page<0||page==$scope.pagination.number||page>=$scope.pagination.totalPages){
              return;
          }
          $scope.page = page;
          $scope.loadItems();
      }
      $scope.changeSize = function() {
          $scope.page =0
          $scope.loadItems();
      }


      pagingScope($scope,{username:false,password:false})


      $scope.init=function (){
          $scope.loadItems()
          $http({
              url:"/user_rest/find_roleAndStore",
              method:"post"
          }).success(function (result) {
              $scope.storeList=result.storeList;
              $scope.roleList = result.roleList;
          }).
          error(function (msg) {
              alert(msg.message)
          })

      }

      $scope.loadItems = function(){
          $http({
              url:"/user_rest/listByPage",
              data:{page : $scope.page, size : $scope.size, sortStr : $scope.sort, sortAscOrDesc : $scope.sortAscOrDesc, 'searchObj' : JSON.stringify($scope.search)},
              method:"post",
              headers:{'Content-Type': 'application/x-www-form-urlencoded'},
              transformRequest: function(obj) {
                  var str = [];
                  for (var s in obj) {
                      str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                  }
                  return str.join("&");
              }
          }).success(function (json) {
              $scope.userList = json.content;
              $scope.pagination = getPagination(json, $scope.page);
              $scope.selectAll=false;
          }).
          error(function (msg) {
              alert(msg.message)
          })

      }
      $scope.init()




      $scope.deleteUser=function () {

          $http({
              url:"/user_rest/delete_user",
              data:{"userId":$scope.currentId,"username":$scope.current.username},
              method:"post"
          }).success(function (result) {
              angular.element("#remove_modal").modal("hide");
              if(result.cmd=="error"){
                  alert(result.msg)
              }else{
                  alertSuccess()
              }

              $scope.loadItems()


          }).
          error(function (msg) {
              angular.element("#remove_modal").modal("hide");
              alert(msg.message)
          })
      }




      $scope.openRemovePopup = function($event,user)
      {
          $event.stopPropagation();
          $scope.currentId=user.id;
          $scope.current.username=user.username;
          angular.element("#remove_modal").modal("show");

      }


      //
      $scope.openEdit = function($event,user) {
          $event.stopPropagation();
          if(user){

              $scope.current=angular.extend($scope.current,user);
              $scope.current.pwd=null;
              $scope.current.pwdConfirm=null;
              $scope.current.error=null;
              $scope.current.expireTime=new Date($scope.current.expireTime)
              angular.element("#editModal").modal("show");
          }else{
              $scope.current={};
              angular.element("#addModal").modal("show");
          }


      }

      $scope.openRelate = function($event,user) {
          $event.stopPropagation();
          $scope.current= angular.extend($scope.current,user);
          $scope.current.expireTime=new Date($scope.current.expireTime)

            for(var j=0;j<$scope.roleList.length;j++){
                $scope.roleList[j].checked=false;
                for(var i=0;i<user.roles.length;i++){
                  if(user.roles[i].id==$scope.roleList[j].id){
                      $scope.roleList[j].checked=true;
                  }
                }

          }

          angular.element("#relateModal").modal("show");



      }

      //重置查询
      $scope.reset=function () {
          $scope.search={};
      }


      $scope.stopPropagation=function ($event) {
          $event.stopPropagation()
      }

  });

</script>
</body>
</html>
